<template>
  <canvas id="random-circle"></canvas>
</template>

<script setup lang="ts">
import { gsap } from "gsap";
import { onMounted } from "vue";
import * as createjs from "@createjs/easeljs";

var stage, circles;
var maxShape = 250;
var colors = ["#B2949D", "#FFF578", "#FF5F8D", "#37A9CC", "#188EB2"];

function initCanvas() {
  stage = new createjs.Stage("random-circle");
  stage.canvas.style.position = "absolute";
  stage.canvas.width = window.innerWidth;
  stage.canvas.height = window.innerHeight;
  stage.canvas.style.top = "0";
  stage.canvas.style.left = "0";
  // 透明
  stage.canvas.style.background = "transparent";
  stage.canvas.style.pointerEvents = "none"; // 禁用 pointer-events
}

function initCircles() {
  circles = [];
  for (var i = 0; i < maxShape; i++) {
    var circle = new createjs.Shape();
    var r = 7;
    var x = window.innerWidth * Math.random();
    var y = window.innerHeight * Math.random();
    var color = colors[Math.floor(i % colors.length)];
    var alpha = 0.2 + Math.random() * 0.5;
    circle.alpha = alpha;
    circle.radius = r;
    circle.graphics.beginFill(color).drawCircle(0, 0, r);
    circle.x = x;
    circle.y = y;
    stage.addChild(circle);
    circles.push(circle);
    circle.movement = "float";
    tweenCircle(circle, undefined);
  }
}

function tweenCircle(c, dir) {
  if (c.tween) c.tween.kill();
  if (dir == "in") {
    c.tween = gsap.to(c, 0.4, {
      x: c.originX,
      y: c.originY,
      ease: "elastic.inOut",
      alpha: 1,
      radius: 5,
      scaleX: 0.4,
      scaleY: 0.4,
      onComplete: function () {
        c.movement = "jiggle";
        tweenCircle(c, undefined);
      },
    });
  } else if (dir == "out") {
    c.tween = gsap.to(c, 0.8, {
      x: window.innerWidth * Math.random(),
      y: window.innerHeight * Math.random(),
      ease: "elastic.inOut",
      alpha: 0.2 + Math.random() * 0.5,
      scaleX: 1,
      scaleY: 1,
      onComplete: function () {
        c.movement = "float";
        tweenCircle(c, undefined);
      },
    });
  } else {
    if (c.movement == "float") {
      c.tween = gsap.to(c, 5 + Math.random() * 3.5, {
        x: c.x + -100 + Math.random() * 200,
        y: c.y + -100 + Math.random() * 200,
        ease: "elastic.inOut",
        alpha: 0.2 + Math.random() * 0.5,
        onComplete: function () {
          tweenCircle(c, undefined);
        },
      });
    } else {
      c.tween = gsap.to(c, 0.05, {
        x: c.originX + Math.random() * 3,
        y: c.originY + Math.random() * 3,
        ease: "elastic.inOut",
        onComplete: function () {
          tweenCircle(c, undefined);
        },
      });
    }
  }
}

function animate() {
  stage.update();
  requestAnimationFrame(animate);
}

onMounted(() => {
  initCanvas();
  initCircles();
  animate();
});
</script>

<style lang="scss" scoped></style>
